package app.sys.utils;


import app.sys.data.entity.BaseEntity;
import app.sys.data.entity.UserInfo;

import java.util.Date;
import java.util.Map;

public abstract class UserUtils {

    //线程变量，存放user实体类信息，即使是静态的与其他线程也是隔离的
    private static final ThreadLocal<UserInfo> userThreadLocal = new ThreadLocal<>();

    //获取当前登录用户
    public static UserInfo getLoginUser() {
        return userThreadLocal.get();
    }

    public static void setLoginUser(UserInfo user) {
        userThreadLocal.set(user);
    }

    public static void removeUser() {
        userThreadLocal.remove();
    }

    /**
     * 设置基础数据
     *
     * @param object 实体类
     */
    public static void setInsetBaseData(Object object) {
        Date date = new Date();
        UserInfo loginUser = getLoginUser();
        if (object instanceof BaseEntity) {
            ((BaseEntity) object).setDelFlag(0);
            ((BaseEntity) object).setCreateTime(date);
            ((BaseEntity) object).setCreateUser(loginUser.getId());
            ((BaseEntity) object).setUpdateTime(date);
            ((BaseEntity) object).setUpdateUser(loginUser.getId());
        } else if (object instanceof Map) {
            Map<String, Object> param = (Map<String, Object>) object;
            param.put("del_flag", "0");
            param.put("create_time", date);
            param.put("create_user", loginUser.getUserCode());
            param.put("update_time", date);
            param.put("update_user", loginUser.getUserCode());
        }
    }

    /**
     * 设置基础数据
     *
     * @param object 实体类
     */
    public static void setUpdateBaseData(Object object) {
        Date date = new Date();
        UserInfo loginUser = getLoginUser();
        if (object instanceof BaseEntity) {
            ((BaseEntity) object).setUpdateTime(date);
            ((BaseEntity) object).setUpdateUser(loginUser.getId());
            ((BaseEntity) object).setDelFlag(1);
        } else if (object instanceof Map) {
            Map<String, Object> param = (Map<String, Object>) object;
            param.put("del_flag", "0");
            param.put("update_user", loginUser.getUserCode());
        }
    }

    /**
     * 设置基础数据
     *
     * @param object 实体类
     */
    public static void setDeleteBaseData(Object object) {
        if (object instanceof BaseEntity) {
            Date date = new Date();
            UserInfo loginUser = getLoginUser();
            ((BaseEntity) object).setUpdateTime(date);
            ((BaseEntity) object).setUpdateUser(loginUser.getId());
            ((BaseEntity) object).setDelFlag(1);
        }
    }
}

